package com.situ.allaia.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.filter.AfterFilter;
import com.alibaba.fastjson2.filter.Filter;
import com.alibaba.fastjson2.filter.PropertyFilter;
import com.situ.allaia.model.Order;
import com.situ.allaia.model.OrderSearchBean;
import com.situ.allaia.service.OrderService;
import com.situ.allaia.util.PaginateInfo;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/orders", produces = "application/json;charset=utf-8")
public class OrderApi {
    private final OrderService orderService;

    public OrderApi(OrderService orderService) {
        this.orderService = orderService;
    }

    //查询所有订单
    @GetMapping
    public String list(OrderSearchBean osb,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "15") Integer limit) {

        PaginateInfo pi = new PaginateInfo(page, limit);
        List<Order> orders = orderService.findAll(osb, pi);

        Map<String, Object> map = Map.of("code", 0, "data", orders, "count", pi.getTotal());

        PropertyFilter filter1 = new PropertyFilter() {
            @Override
            public boolean apply(Object o, String s, Object o1) {
                if (o instanceof Order) {
                    if ("items".equals(s)) {
                        return false;
                    }
                }
                return true;
            }
        };

        AfterFilter filter2 = new AfterFilter() {
            @Override
            public void writeAfter(Object o) {
                if (o instanceof Order order) {
                    writeKeyValue("longId", order.getId().toString());
                }
            }
        };

        String json = JSON.toJSONString(map, new Filter[]{filter2, filter1});

        return json;
    }

    //发货操作
    @PatchMapping("/send")
    public Map<String, Object> send(Long[] ids) {
        int rows = orderService.sendByIds(List.of(ids));
        if (rows>0){
            return Map.of("success", rows > 0, "rows", rows);
        }else{
            return Map.of("error","您选择的订单存在已发货或已确认,请重新选择");
        }

    }
}
